﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace ProjectDanmaku.Entity
{
    public class EntityLayer : MonoBehaviour
    {
        public int sortingOrder = 0;
        
        private readonly Dictionary<Type, EntitySubLayer> _entitySubLayerDict = new ();
        private readonly List<EntitySubLayer> _entitySubLayers = new();

        private void InitSubLayers()
        {
            var comps = GetComponentsInChildren<EntitySubLayer>();

            foreach (var comp in comps)
            {
                var dataType = comp.GetEntityDataType();
                _entitySubLayerDict[dataType] = comp;
                _entitySubLayers.Add(comp);
            }
        }

        private void TickSubLayers()
        {
            foreach (var subLayer in _entitySubLayers)
            {
                if (subLayer.enabled)
                    subLayer.Tick();
            }
        }

        protected void Start()
        {
            InitSubLayers();
        }

        protected void Update()
        {
            TickSubLayers();
        }

        public void AddEntity(EntityData entityData)
        {
            var type = typeof(EntityData);
            
            if (_entitySubLayerDict.TryGetValue(type, out var subLayer))
            {
                subLayer.AddEntity(entityData);
            }
        }
    }
}